package com.xyy.saas.payment.callback.core.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.xyy.elasticjob.client.annotation.ElasticJobConf;
import com.xyy.saas.payment.adpater.RouteManager;
import com.xyy.saas.payment.adpater.impl.FuminAdapter;
import com.xyy.saas.payment.callback.core.result.CallbackRunner;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.cores.bo.QueryResultBo;
import com.xyy.saas.payment.cores.vo.CallbackResultVo;
import com.xyy.saas.payment.dao.model.PayResultOrder;
import com.xyy.saas.payment.dao.model.RefundOrder;
import com.xyy.saas.payment.merchant.core.dto.QueryTransactionStatusDto;
import com.xyy.saas.payment.payment.core.service.RefundOrderService;
import com.xyy.saas.payment.service.PayResultOrderService;
import com.xyy.saas.payment.util.ApolloUtil;
import com.xyy.saas.payment.util.DateUtil;
import com.xyy.saas.payment.util.JSONUtils;
import com.xyy.saas.payment.util.TimestampConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 同步退款状态
 */
@Slf4j
@ElasticJobConf(name = "com.xyy.saas.payment.callback.core.job.SyncRefundStatusJobExecOneMinute", cron = "0 0/1 * * * ? ")
public class SyncRefundStatusJob implements SimpleJob {
    @Resource
    private RefundOrderService refundOrderService;
    @Resource
    private PayResultOrderService payResultOrderService;
    @Resource
    private RouteManager routeManager;
    @Resource
    private CallbackRunner callbackRunner;
    @Resource
    private FuminAdapter fuminAdapter;

    @Override
    public void execute(ShardingContext shardingContext) {
        // 平安创建
        syncStatus(RefundOrder.STATUS_CREATE,Constants.CHANNEL_PINGAN_NAME);
        // 平安退款中
        syncStatus(RefundOrder.STATUS_IN,Constants.CHANNEL_PINGAN_NAME);
        // 富民退款中
//        syncStatus(RefundOrder.STATUS_IN,Constants.CHANNEL_FUMIN_BANK_NAME);
        // 京东绑卡退款中
        syncStatus(RefundOrder.STATUS_IN, Constants.CHANNEL_JD_CARD_NAME);
        // 京东聚合支付退款中
        syncStatus(RefundOrder.STATUS_IN, Constants.CHANNEL_JDAGGREGATE_NAME);
    }

    public void syncStatus(Byte status,String channelPrefix) {
        long startTime = System.currentTimeMillis();
        log.info("SyncRefundStatusJob#execute start.");

        int pageOffset = 0;
        int pageSize = 50;

        while(true) {
            List<RefundOrder> items = refundOrderService.selectListByStatusAndPayChannel(channelPrefix, status, pageOffset, pageSize);

            if(CollectionUtils.isEmpty(items)) {
                break;
            }

            for(RefundOrder item : items) {
                try {
                    PayResultOrder resultOrder = payResultOrderService.selectByPayNoAndChannel(item.getPayNo(), item.getChannel());

                    String transactionNo = item.getRefundNo();
                    if(org.apache.commons.lang.StringUtils.isNotBlank(item.getChannelRefundNo()) && item.getChannelRefundNo().startsWith(Constants.TOTAL_ORDER_NUMBER_PREFIX)) {
                        transactionNo = item.getChannelRefundNo().substring(NumberUtils.INTEGER_ONE);
                    }

                    QueryTransactionStatusDto queryTransactionStatusDto = QueryTransactionStatusDto.build(resultOrder.getBusinessType(), resultOrder.getBusinessOrderType(), transactionNo, QueryTransactionStatusDto.TRADE_TYPE_REFUND, getPayeeAccountId(item.getUserId()), item.getUpdateTime(), resultOrder.getPayNo(),resultOrder.getPayChannel());
                    QueryResultBo queryResultBo = null;
                    // 平安*渠道
                    if (Constants.CHANNEL_PINGAN_NAME.equals(channelPrefix)) {
                        queryResultBo = routeManager.queryTransactionStatus(queryTransactionStatusDto, item.getChannel());
                    }
                    // 富民渠道
                    else if (Constants.CHANNEL_FUMIN_BANK_NAME.equals(channelPrefix)){
                        queryResultBo = fuminAdapter.queryTransactionStatus(queryTransactionStatusDto);
                    }
                    // 京东渠道
                    else if (Constants.CHANNEL_JD_CARD_NAME.equals(channelPrefix) || Constants.CHANNEL_JDAGGREGATE_NAME.equals(channelPrefix)) {
                        queryResultBo = routeManager.queryTransactionStatus(queryTransactionStatusDto, item.getChannel());
                    }

                    if(queryResultBo == null) {
                        if(RefundOrder.STATUS_CREATE.equals(item.getStatus())) {
                            // 1.更新退款结果
                            item.setStatus(RefundOrder.STATUS_FAIL);
                            refundOrderService.update(item);
                        }
                        continue;
                    }

                    switch(queryResultBo.getStatus()) {
                        case QueryResultBo.PROCESSING:
                            break;
                        case QueryResultBo.FINISHED:
                            // Long unixTime = queryResultBo.getSuccessTime() / 1000;
                            Long unixTime = queryResultBo.getSuccessTime();
                            // 1.更新退款结果
                            item.setStatus(RefundOrder.STATUS_FINISH);
                            Date successDate = TimestampConverter.safeConvert(unixTime);
                            item.setSuccessTime(successDate != null ? successDate : DateUtil.unixToDate(unixTime));
                            refundOrderService.update(item);
                            // 2.通知业务
                            callbackRunner.callback(item.getRefundNo(), CallbackResultVo.TYPE_REFUND_SUCCESS, item.getAmount(), unixTime, item.getCallbackAddress(), resultOrder.getMerchantId(), item.getBusinessRefundNo());
                            break;
                        case QueryResultBo.FAILED:
                            // 1.更新退款结果
                            item.setStatus(RefundOrder.STATUS_FAIL);
                            refundOrderService.update(item);
                            // 2.通知业务
                            String failMsg = (StringUtils.isBlank(queryResultBo.getFailureCode()) ? "" : queryResultBo.getFailureCode()) + ":" + (StringUtils.isBlank(queryResultBo.getFailureMsg()) ? "" : queryResultBo.getFailureMsg());
                            callbackRunner.callback(item.getRefundNo(), CallbackResultVo.TYPE_REFUND_FAIL, item.getAmount(), 0L, item.getCallbackAddress(), resultOrder.getMerchantId(), item.getBusinessRefundNo(), failMsg);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported Operation refund status. queryResultBo=" + JSONUtils.toJSON(queryResultBo));
                    }
                }
                catch(Exception ex) {
                    log.error("SyncRefundStatusJob#execute error {},{}" ,item.getRefundNo(),item.getBusinessRefundNo(), ex);
                }
            }
            if(items.size() < pageSize) {
                break;
            }
            pageOffset += pageSize;
        }
        log.info("SyncRefundStatusJob#execute end. cost={}", (System.currentTimeMillis() - startTime));
    }

    /**
     * 获取收款人信息
     */
    private String getPayeeAccountId(String accountId) {
        if(StringUtils.isBlank(accountId)) {
            return accountId;
        }
        return Objects.equals(ApolloUtil.getProperty(Constants.POP_DIRECT_PAY_YBM_TECH_USER_ID), accountId) ? ApolloUtil.getProperty(Constants.EC_POP_BIG_SHOP_PINGAN_ACCOUNT_ID) : accountId;
    }

}
